/**
 *  登録内容をデータベースに登録するクラス
 *  @author Komori
 *  @version 1.0
 */

package manager;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.DBManager;

public class WriteServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		req.setCharacterEncoding("UTF-8");

		// SQL文を用意
		String sql = "insert into managers(name, ruby, upper_level, password, delete_flag) values(?, ?, ?, ?, 0)";

		// 各入力パラメータの取得
		String name = req.getParameter("name");
		String ruby = req.getParameter("ruby");
		String levelStr = req.getParameter("level");
		int level = Integer.parseInt(levelStr);
		String password = req.getParameter("password");

		Connection con = null;
		PreparedStatement ps = null;

		// 成功メッセージ格納変数
		String msg = null;

		try {
			con = DBManager.getConnection();
			ps = con.prepareStatement(sql);

			// パラメータをSQL文に挿入
			ps.setString(1, name);
			ps.setString(2, ruby);
			ps.setInt(3, level);
			ps.setString(4,  password);

			ps.executeUpdate();

			msg = "登録しました";

		} catch(SQLException e) {
			throw new ServletException(e);
		} finally {
			if(ps != null) {
				try {
					ps.close();
				} catch(SQLException ignore) {
					// none
				}
			}
			if(con != null) {
				try {
					con.close();
				} catch(SQLException ignore) {
					// none
				}
			}
		}
		// 担当者一覧画面に遷移
		if(msg != null) {
			req.setAttribute("msg", msg);
		}
		req.getRequestDispatcher("./ListServlet").forward(req, resp);

	}

}
